// 获取浏览器代理
var USER_AGENT = navigator.userAgent || "";
//倒计时器
var timerCount;
/**
 * 检测class
 * @param {*} elements
 * @param {*} cName
 */
function hasClass(elements, cName) {
  return !!elements.className.match(new RegExp("(\\s|^)" + cName + "(\\s|$)"));
}

/**
 * 添加class
 * @param {*} elements
 * @param {*} cName
 */
function addClass(elements, cName) {
  if (!hasClass(elements, cName)) {
    elements.className += " " + cName;
  }
}

/**
 * 删除Class
 * @param {*} elements
 * @param {*} cName
 */
function removeClass(elements, cName) {
  if (hasClass(elements, cName)) {
    elements.className = elements.className.replace(
      new RegExp("(\\s|^)" + cName + "(\\s|$)"),
      " "
    );
  }
}

/**
 * 获取地址栏参数
 * @param {*} name
 */
function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

/**
 * 跳转支付宝链接
 * */
function gotoAlipayApp() {
  window.location.href =
    "alipays://platformapi/startapp?appId=20000067&url=" +
    encodeURIComponent(window.location.href);
}

/**
 * 创建定时器
 * @param {*} startTime
 */
function createTimer(startTime) {
  //获取起始date
  var startDate = new Date(startTime);
  var now = new Date();
  var tenM = 10 * 60 * 1000;
  //折算成秒剩余多少秒
  var maxtime = (startDate.getTime() + tenM - now.getTime()) / 1000;

  if (timerCount) {
    clearTimeout(timerCount);
    timerCount = null;
  }

  timerCount = setTimeout(function() {
    countDown(maxtime);
  }, 1000);
}

/**
 * 定时器
 * @param {*} maxtime
 */
function countDown(maxtime) {
  if (maxtime >= 0) {
    minutes = Math.floor(maxtime / 60);
    seconds = Math.floor(maxtime % 60);

    msg =
      (minutes > 9 ? minutes : "0" + minutes) +
      "分" +
      (seconds > 9 ? seconds : "0" + seconds) +
      "秒";
    document.getElementById("countDownSpan").innerHTML = msg;
    --maxtime;

    //继续执行定时器剩余部分
    setTimeout(function() {
      countDown(maxtime);
    }, 1000);
  } else {
    clearTimeout(timerCount);
    timerCount = null;
    goToErrPage("超出支付时间，交易失效");
  }
}

/**
 * 初始化化二维码
 * @param {*} url
 */
function initQrcode() {
  var url = window.location.href;
  if (!url) {
    console.error("二维码url未获取到");
    return;
  }

  //提供生成二维码机制
  var qrcode = new QRCode(document.getElementById("qrcode"), {
    text: window.location.href,
    width: 140,
    height: 140,
    colorDark: "#000000",
    colorLight: "#ffffff",
    correctLevel: QRCode.CorrectLevel.H
  });
}

///支付宝ua判断
function isAplipayUA(ua) {
  return /alipayclient/.test(ua.toLowerCase());
}

/**
 * 退出支付宝window窗体
 */
function returnApp() {
  AlipayJSBridge.call("exitApp");
}

/**
 * alipay ready函数
 */
//监听resume事件：alipay app客户端中才有的事件
document.addEventListener("resume", function(a) {
  returnApp();
});

//alipay客户端内部访问
function onAliPayReady(pid, oid, money) {
  function ready(a) {
    window.AlipayJSBridge
      ? a && a()
      : document.addEventListener("AlipayJSBridgeReady", a, !1);
  }

  ready(function() {
    try {
      var a = {
        actionType: "scan",
        u: pid,
        a: money,
        m: oid,
        biz_data: {
          s: "money",
          u: pid,
          a: money,
          m: oid
        }
      };
    } catch (b) {
      returnApp();
    }

    AlipayJSBridge.call(
      "startApp",
      {
        appId: "20000123",
        param: a
      },
      function(a) {
        alert(JSON.stringify(a));
      }
    );
  });
}

function goToErrPage(txt) {
  var str = encodeURI(encodeURI(txt));
  window.location.href = "./error.html?errMsg=" + str;
}

/**
 * 查询交易信息
 * @param {*} tid
 */
function queryTradeInfo(tid) {
  axios({
    method: "get",
    url: "/openApi/api/getAliPayment",
    params: {
      id: tid
    }
  }).then(
    function(res) {
      var data = res.data || {};
      if (res.status == 200 && data.code == 0) {
        var ret = data.data || {};
        var oid = ret.o;
        var money = ret.m;
        var pid = ret.u;
        var t = ret.t;

        if (!pid || !money) {
          alert("生成的支付参数无效!");
          return;
        }

        //支付宝内部直接调用此逻辑
        if (isAplipayUA(USER_AGENT)) {
          onAliPayReady(pid, oid, money);
          return;
        }

        //数据有效
        var appId = document.getElementById("appId");
        //显示当前页面
        if (hasClass(appId, "hide")) {
          removeClass(appId, "hide");
        }

        //创建定时器
        createTimer(t);

        document.getElementById("mSpan").innerText = "￥ " + ret.m;
        document.getElementById("oidSpan").innerText = oid;

        initQrcode();
      } else goToErrPage(data.msg);
    },
    function(err) {
      console.log(err);
      var statusText = (err || {}).statusText || "支付通道异常";
      goToErrPage(statusText);
    }
  );
}

//优先判断是否含有交易ID
var id = getQueryString("id");
if (!id) {
  goToErrPage("无效的地址，缺省交易ID");
} else {
  queryTradeInfo(id);
}
